<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="scId">
        <el-select v-model="queryParams.scId" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.name">{{user.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId" >
        <el-select v-model="queryParams.supplierId" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.name">{{user.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购员" prop="purchaserId" >
        <el-select v-model="queryParams.purchaserId" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.name">{{user.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入操作人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核人" prop="approveBy" >
        <el-select v-model="queryParams.approveBy" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.name">{{user.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择操作时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核人" prop="approveBy" >
        <el-select v-model="queryParams.approveBy" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.name">{{user.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" prop="approveTime">
        <el-date-picker clearable
          v-model="queryParams.approveTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择审核时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status" >
        <el-select v-model="queryParams.status" @keyup.enter.native="handleQuery" clearable>
          <el-option value="0" label="待审核">待审核</el-option>
          <el-option value="3" label="审核通过">审核通过</el-option>
          <el-option value="6" label="审核拒绝">审核拒绝</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:PurchaseOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:PurchaseOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:PurchaseOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="PurchaseOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="left" prop="id" width="200px"/>
      <el-table-column label="单号" align="left" prop="code" width="200px"/>
      <el-table-column label="仓库编号" align="left" prop="scCode" width="100px"/>
      <el-table-column label="仓库名称" align="left" prop="scName" width="100px"/>
      <el-table-column label="供应商编号" align="left" prop="supplierCode" width="100px"/>
      <el-table-column label="供应商名称" align="left" prop="supplierName" width="100px"/>
      <el-table-column label="采购员" align="left" prop="purchaserName" width="100px"/>
      <el-table-column label="采购金额" align="left" prop="totalAmount" width="100px"/>
      <el-table-column label="采购数量" align="left" prop="totalNum" width="100px"/>
      <el-table-column label="赠品数量" align="left" prop="totalGiftNum" width="100px"/>
      <el-table-column label="预计到货日期" align="left" prop="expectArriveDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectArriveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" align="left" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="left" prop="createBy" width="100px"/>
      <el-table-column label="状态" align="left" prop="status" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">待审核</span>
          <span v-if="scope.row.status == 3">审核通过</span>
          <span v-if="scope.row.status == 6">审核拒绝</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="left" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="left" prop="approveBy" width="100px"/>
      <el-table-column label="备注" align="left" prop="description" width="100px"/>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right" width="200px">
        <template slot-scope="scope">
          <el-button
            size="medium"
            type="text"
            @click="selectOrder(scope.row)"
            v-hasPermi="['system:PurchaseOrder:edit']"
          >查看</el-button>
          <el-button
            size="medium"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:PurchaseOrder:edit']"
          >修改</el-button>
          <el-button
            size="medium"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:PurchaseOrder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看按钮 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;"><p>仓库：{{ this.form.scName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>供应商：{{ this.form.supplierName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>采购员：{{ this.form.purchaserName }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>预计到货日期：{{ this.form.expectArriveDate }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>状态：<span :style="{color: statusColor}">{{ this.form.status==0 ? '待审核' : (this.form.status==3 ? '审核通过' : '审核拒绝') }}</span></p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>操作人：{{ this.form.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>操作时间：{{ this.form.createTime }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>审核人：{{ this.form.approveBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>审核时间：{{ this.form.approveTime }}</p></div>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table height="400px" v-loading="loading" :data="this.tblPurchaseOrderDetailList" @selection-change="handleSelectionChange">
          <el-table-column label="商品编号" align="left" prop="baseDataProduct.id" width="200px"/>
          <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="200px"/>
          <el-table-column label="商品SKU编号" align="left" prop="baseDataProduct.skuCode" width="100px"/>
          <el-table-column label="商品外部编号" align="left" prop="baseDataProduct.externalCode" width="100px"/>
          <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px"/>
          <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px"/>
          <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px"/>
          <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px"/>

          <el-table-column label="采购价（元）" align="left" prop="taxPrice" width="100px"/>
          <el-table-column label="税率（%）" align="left" prop="taxRate" width="100px"/>
          <el-table-column label="是否赠品" align="left" prop="isGift" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.isGift == 0 ? '否' : '是' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采购数量" align="left" prop="orderNum" width="180"/>
          <el-table-column label="采购含税金额" align="left" prop="" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.taxPrice * scope.row.orderNum }}</span>
            </template>‘
          </el-table-column>
          <el-table-column label="备注" align="left" prop="description" width="100px"/>
        </el-table>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;">合计</h3>
        <div style="display: inline-block;margin-left:50px">
          采购数量：<input type="text" v-model="this.form.totalNum" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled>
        </div>
        <div style="display: inline-block;margin-left:50px">
          赠品数量：<input type="text" v-model="this.form.totalGiftNum" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled>
        </div>
        <div style="display: inline-block;margin-left:50px">
          含税总金额：<input type="text" v-model="this.form.totalAmount" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled>
        </div>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;margin-left: 10px">约定支付</h3>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-table :data="tblPurchaseOrderDetailList" height="300px" :row-class-name="rowTblPurchaseOrderDetailIndex" @selection-change="handleTblPurchaseOrderDetailSelectionChange" ref="tblPurchaseOrderDetail">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="支付方式" prop="productId" width="200">
              <template slot-scope="scope">
<!--                <el-input v-model="scope.row.productId" placeholder="请输入商品ID" disabled/>-->
                <el-select v-model="queryParams.approveBy" @keyup.enter.native="handleQuery" clearable>
                  <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.name">{{user.name}}</el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="支付金额" prop="orderNum" width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.orderNum" placeholder="请输入采购数量" disabled/>
              </template>
            </el-table-column>
            <el-table-column label="支付记录" prop="taxPrice" width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.orderNum" placeholder="请输入采购数量" disabled/>
              </template>
            </el-table-column>
            <el-table-column label="" prop="" width="280"/>
          </el-table>
        </el-form>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px;text-align: right">
        <label >备注： </label>
        <textarea style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid" disabled/>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
<!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
<!--        <el-button @click="cancel">取 消</el-button>-->
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchaseOrder, getPurchaseOrder, delPurchaseOrder, addPurchaseOrder, updatePurchaseOrder } from "@/api/system/PurchaseOrder";
import { listUser} from "@/api/system/erpUser";
import Layout from "@/layout/index.vue";
import {listTblOrderPayType}from "@/api/system/TblOrderPayType"

export default {
  name: "PurchaseOrder",
  components: {Layout},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTblPurchaseOrderDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      PurchaseOrderList: [],
      //用户列表
      UserList: [],
      //支付方式
      OrderPayTypeList: [],
      // 采购订单明细表格数据
      tblPurchaseOrderDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //弹窗状态颜色
      statusColor:"rgb(100, 100, 100)",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        supplierId: null,
        purchaserId: null,
        createBy: null,
        createTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
      },
      orderPayTypeParams:{
        orderId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "单号不能为空", trigger: "blur" }
        ],
        scId: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
        totalNum: [
          { required: true, message: "采购数量不能为空", trigger: "blur" }
        ],
        totalGiftNum: [
          { required: true, message: "赠品数量不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "采购金额不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "操作人不能为空", trigger: "blur" }
        ],
        createById: [
          { required: true, message: "创建人编号不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "操作时间不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "修改人不能为空", trigger: "blur" }
        ],
        updateById: [
          { required: true, message: "修改人编号不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      listPurchaseOrder(this.queryParams).then(response => {
        this.PurchaseOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
      });
    },
    /** 查询支付方式 */
    getOrderPayType() {
      this.loading = true;
      this.orderPayTypeParams.orderId = this.form.id;
      listTblOrderPayType(this.orderPayTypeParams).then(response => {
        this.OrderPayTypeList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        scId: null,
        scName: null,
        supplierId: null,
        supplierName: null,
        purchaserId: null,
        purchaserName: null,
        expectArriveDate: null,
        totalNum: null,
        totalGiftNum: null,
        totalAmount: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
        refuseReason: null
      };
      this.tblPurchaseOrderDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.$router.push({
        path:'/PurchaseOrder/add',
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      // console.log(row);
      // console.log(this.form.productId);
      this.$router.push({
        path:'/PurchaseOrder/update',
        query:{
          id: id,
        }
      })
    },
    // 查看按钮
    selectOrder(row) {
      // this.reset();
      // this.form =row
      // this.open = true;
      // this.title = "查看采购订单";
      //
      // if (row.status==0){
      //   this.statusColor = "rgb(100, 100, 100)";
      // }else if (row.status==3){
      //   this.statusColor = "rgb(82, 196, 26)";
      // }else {
      //   this.statusColor = "rgb(255, 0, 0)";
      // }


      const id = row.id || this.ids
      getPurchaseOrder(id).then(response => {
        this.form = response.data;
        this.tblPurchaseOrderDetailList = response.data.tblPurchaseOrderDetailList;
        this.open = true;
        this.title = "查看采购订单";
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }

      this.getOrderPayType();
    },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       this.form.tblPurchaseOrderDetailList = this.tblPurchaseOrderDetailList;
    //       if (this.form.id != null) {
    //         updatePurchaseOrder(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addPurchaseOrder(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购订单编号为"' + ids + '"的数据项？').then(function() {
        return delPurchaseOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 采购订单明细序号 */
    rowTblPurchaseOrderDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 采购订单明细添加按钮操作 */
    handleAddTblPurchaseOrderDetail() {
      let obj = {};
      obj.productId = "";
      obj.orderNum = "";
      obj.taxPrice = "";
      obj.isGift = "";
      obj.taxRate = "";
      obj.description = "";
      obj.orderNo = "";
      obj.receiveNum = "";
      this.tblPurchaseOrderDetailList.push(obj);
    },
    /** 采购订单明细删除按钮操作 */
    handleDeleteTblPurchaseOrderDetail() {
      if (this.checkedTblPurchaseOrderDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的采购订单明细数据");
      } else {
        const tblPurchaseOrderDetailList = this.tblPurchaseOrderDetailList;
        const checkedTblPurchaseOrderDetail = this.checkedTblPurchaseOrderDetail;
        this.tblPurchaseOrderDetailList = tblPurchaseOrderDetailList.filter(function(item) {
          return checkedTblPurchaseOrderDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTblPurchaseOrderDetailSelectionChange(selection) {
      this.checkedTblPurchaseOrderDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/PurchaseOrder/export', {
        ...this.queryParams
      }, `PurchaseOrder_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
